﻿using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Configuration;
using AT.IBMS.Framework.Configuration;
using System;

namespace AT.IBMS.Framework.WeiXin
{
    public class WeiXinHandler : IHttpHandler
    {
        /// <summary>
        /// 您将需要在您网站的 web.config 文件中配置此处理程序，
        /// 并向 IIS 注册此处理程序，然后才能进行使用。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // 如果无法为其他请求重用托管处理程序，则返回 false。
            // 如果按请求保留某些状态信息，则通常这将为 false。
            get
            {
                return true;
            }
        }


        private WeiXinProviderBase CreateWeiXinProvider(WeiXinElement section)
        {

            ProviderSettings providerSettings;

            providerSettings = section.Providers[section.ProviderName];
            return (WeiXinProviderBase)ProvidersHelper.
                InstantiateProvider(providerSettings,
                typeof(WeiXinProviderBase));

        }

        public void ProcessRequest(HttpContext context)
        {

            WeiXinProviderBase provider;
            WeiXinElement section;

            section = FrameworkManager.FrameworkConfigurationSettings.WeiXin;
            provider = CreateWeiXinProvider(section);

            #region 接入验证

            if (context.Request.HttpMethod.ToUpper() == "GET")
            {

                string signature; //微信加密签名
                string timestamp; //时间戳
                string nonce; //随机数
                string echostr; //随机字符串

                signature = context.Request.QueryString["signature"];
                timestamp = context.Request.QueryString["timestamp"];
                nonce = context.Request.QueryString["nonce"];
                echostr = context.Request.QueryString["echostr"];

                if (provider.CheckSignature(signature, timestamp, nonce))
                {
                    context.Response.Write(echostr);
                }

            }

            #endregion

            #region 接收到消息

            else if (context.Request.HttpMethod.ToUpper() == "POST")
            {

                Dictionary<string, string> requestDic;
                StreamReader reader;
                string xml;

                using (reader = new StreamReader(context.Request.InputStream))
                {
                    xml = reader.ReadToEnd();
                    requestDic = provider.ParseXml(xml);
                }



            }

            #endregion

        }

        #endregion
    }
}
